package dialog;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.zx.theline.jclr.JclrActivity;
import com.example.zx.theline.R;

import org.apache.http.Header;

import java.util.ArrayList;
import java.util.List;

import GsonBean.JcxxChakanBean;
import GsonBean.RjhSgxmListBean;
import GsonBean.SuccessBean;
import GsonBean.post.TgysPost;
import Utils.RefreshManager;
import app.MyApplication;
import base.BaseDialog;
import network.NetWorkApi;
import network.ObjectHttpResponseHandler;
import Utils.MyToast;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Ren on 2017/6/29.
 */
//复工审核
public class FgshDialog extends BaseDialog {
    //标题
    TextView title;

    //确认
    TextView confirm;

    //取消
    TextView cancel;


    //审核意见
    EditText shyj;

    //停工项目
    TextView tgxm;

    JcxxChakanBean mJcxxChakanBean;

    Activity baseActivity;

    //停工项目 spinner
    Spinner tgxmSpinner;
    boolean isSpinnerFirst = true;

    SpinnerAdapter mSpinnerAdapter;

    List<RjhSgxmListBean> sgxmList;

    //停工项目数量
    int tgxmNum = 0;


    public FgshDialog(Context context, JcxxChakanBean mBean, Activity baseActivity) {
        super(context);
        this.mJcxxChakanBean = mBean;
        this.baseActivity = baseActivity;
    }

    public FgshDialog(Context context, int themeResId) {
        super(context, themeResId);
    }

    protected FgshDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_fgsh);
        InitView();
        InitData();
        InitListen();
    }

    @Override
    protected void InitView() {
        confirm = (TextView) findViewById(R.id.confirm);
        cancel = (TextView) findViewById(R.id.cancel);
        shyj = (EditText) findViewById(R.id.shyj);
        title = (TextView) findViewById(R.id.title);
        tgxm = (TextView) findViewById(R.id.tgxm);
        tgxmSpinner = (Spinner) findViewById(R.id.tgxmspinner);

        sgxmList = new ArrayList<>();

        //                    tgxmSpinner.setVisibility(View.GONE);
        if (mJcxxChakanBean.getJcbShdwList() != null) {
            mSpinnerAdapter = new SpinnerAdapter();
            tgxmSpinner.setAdapter(mSpinnerAdapter);

            //停工项目spinner初始化
            //根据是否选中 确定spinner中是否选中
            //根据是否为停工项目 向sgxmlist中添加初始数据
            for (int j = 0; j < mJcxxChakanBean.getRjhSgxmList().size(); j++) {
                RjhSgxmListBean bean = mJcxxChakanBean.getRjhSgxmList().get(j);
                if (bean.isTgXm()) {
                    sgxmList.add(bean);
                    tgxmNum++;
                }
            }
            setTgxmText();
            tgxmSpinner.setVisibility(View.VISIBLE);
        } else {
            tgxmSpinner.setVisibility(View.GONE);
        }
    }

    @Override
    protected void InitData() {

    }

    @Override
    protected void InitListen() {

        //取消spinner默认选中项
        tgxmSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isSpinnerFirst) {
                    view.setVisibility(View.INVISIBLE);
                }

                isSpinnerFirst = false;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TgysPost mPost = new TgysPost();

                //根据选中需要恢复的停工项目，确定停工审核同意，并设置停工数据
                //1.全部同意（Y）：选中的复工项目ID == 停工项目ID
                //2.不同意(N)：没有选中复工项目
                //2.部分同意(N)：选中的复工项目 != 停工项目ID

                //选中的复工项目数量为0 同意


                if (shyj.getText().toString().length() == 0) {
                    MyToast.showToast("请输入审核意见");
                    return;
                }
                if (shyj.getText().length() > 0 && shyj.getText().toString().trim().length() == 0) {
                    MyToast.showToast("请不要输入空格");
                    return;
                }
                if (sgxmList.size() == 0) {
                    mPost.setWhetherAuditAgree("N");
                }
                //选中的复工项目数量等于所有停工项目数量 全部同意
                if (sgxmList.size() == tgxmNum) {
                    mPost.setWhetherAuditAgree("Y");
                }
                //0!=选中的复工项目数量!=所有停工项目数量 部分同意
                if (sgxmList.size() != 0 && sgxmList.size() != tgxmNum) {
                    mPost.setWhetherAuditAgree("N");
                }

                mPost.setTgxmId(getTgxmId());
                mPost.setJdjhjcbId(mJcxxChakanBean.getRjdjhjcbInfo().getJdjhjcbId());
                mPost.setTgshyj(shyj.getText().toString());
                mPost.setFldw(MyApplication.getmLoginUser().getUserUnitName());
                mPost.setFlrName(MyApplication.getmLoginUser().getTrueName());
                mPost.setXgrId(MyApplication.getmLoginUser().getUserDisplayName());

                List<TgysPost.LjyyxRjdjhjcbShdw> shdwList = new ArrayList<TgysPost.LjyyxRjdjhjcbShdw>();
                TgysPost.LjyyxRjdjhjcbShdw shdwBean = new TgysPost.LjyyxRjdjhjcbShdw();
                shdwBean.setJdjhbBh(mJcxxChakanBean.getRjdjhjcbInfo().getRjdjhbBh());
                shdwBean.setDwId(MyApplication.getmLoginUser().getUserUnitId());
                shdwBean.setDwmc(MyApplication.getmLoginUser().getUserUnitName());
                shdwBean.setShrlogin(MyApplication.getmLoginUser().getUserDisplayName());
                shdwBean.setShrname(MyApplication.getmLoginUser().getTrueName());
                shdwBean.setShrphone(MyApplication.getmLoginUser().getUserMobilephone());

                shdwList.add(shdwBean);
                mPost.setJcbShdwList(shdwList);


                MyApplication.ShowWaitDialog(getContext());
                NetWorkApi.Fgsh(mPost, new Callback<SuccessBean>() {
                            @Override
                            public void onResponse(Call<SuccessBean> call, Response<SuccessBean> response) {
                                try {
                                    MyApplication.HideWaitDialog();
                                    SuccessBean successBean = response.body();
                                    if (successBean.getMsg().equals("false")) {
                                        MyToast.showToast("复工审核失败，新检查网络后重新预审");
                                        return;
                                    }
                                    if (successBean.getMsg().equals("success")) {
                                        MyToast.showToast("复工审核成功");
                                        RefreshManager.Jdjc.RefreshJdjclrxx();
                                        RefreshManager.Jdjc.RefreshJdjcdcl();
                                        RefreshManager.Jdjc.RefreshJdjcycl();
                                        getContext().startActivity(new Intent(getContext(), JclrActivity.class));
                                    }
                                } catch (Exception e) {
                                    MyToast.showFail();
                                }
                            }

                            @Override
                            public void onFailure(Call<SuccessBean> call, Throwable t) {
                                MyToast.showFail();
                            }
                        }
                );

            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FgshDialog.this.dismiss();
            }
        });

    }

    class SpinnerAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mJcxxChakanBean.getRjhSgxmList().size();
        }

        @Override
        public Object getItem(int position) {
            return mJcxxChakanBean.getRjhSgxmList().get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {


            ViewHolder mViewHolder;
            if (convertView == null) {
                convertView = View.inflate(getContext(), R.layout.bcfxd_listview, null);
                mViewHolder = new ViewHolder();
                mViewHolder.mCheckBox = (CheckBox) convertView.findViewById(R.id.checkbox);
                convertView.setTag(mViewHolder);
            } else {
                mViewHolder = (ViewHolder) convertView.getTag();
            }


            mViewHolder.mCheckBox.setText(mJcxxChakanBean.getRjhSgxmList().get(position).getSgxmmc());
            mViewHolder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        addSgxm(position);
                    } else {
                        DelectSgxm(position);
                    }
                }
            });

            if (mJcxxChakanBean.getRjhSgxmList().get(position).isTgXm()) {
                mViewHolder.mCheckBox.setChecked(true);
            } else {
                mViewHolder.mCheckBox.setChecked(false);
            }


            return convertView;
        }

        class ViewHolder {
            CheckBox mCheckBox;

        }
    }


    public void addSgxm(int position) {
        if (!sgxmList.contains(mJcxxChakanBean.getRjhSgxmList().get(position)))
            sgxmList.add(mJcxxChakanBean.getRjhSgxmList().get(position));
        mJcxxChakanBean.getRjhSgxmList().get(position).setTgXm(true);
        String s = sgxmList.toString();
        s = s.substring(1, s.length() - 1);
        tgxm.setText(s);
    }

    public void DelectSgxm(int position) {
        if (sgxmList.contains(mJcxxChakanBean.getRjhSgxmList().get(position)))
            sgxmList.remove(mJcxxChakanBean.getRjhSgxmList().get(position));
        mJcxxChakanBean.getRjhSgxmList().get(position).setTgXm(false);
        String s = sgxmList.toString();
        s = s.substring(1, s.length() - 1);
        tgxm.setText(s);
    }

    public void setTgxmText() {
        String s = "";
        for (RjhSgxmListBean item : mJcxxChakanBean.getRjhSgxmList()) {
            if (item.isTgXm()) {
                s += item.getSgxmmc() + ",";
            }
        }
        if (s.length() > 0)
            s = s.substring(0, s.length() - 1);
        tgxm.setText(s);
    }

    //与其他界面不同，该界面选中的是复工的项目 所以获取停工项目ID时 选中的项目 对象中Tgxm字段为true 代表与其他界面都相反，true代表该项目被复工
    public String getTgxmId() {
        String s = "";
        for (RjhSgxmListBean item : mJcxxChakanBean.getRjhSgxmList()) {
            if (!item.isTgXm()) {
                s += item.getSgxmlbzdId() + ",";
            }
        }
        if (s.length() > 0)
            s = s.substring(0, s.length() - 1);
        return s;
    }
}
